package com.hkrt.arch;

import android.arch.lifecycle.LifecycleRegistry;
import android.arch.lifecycle.LifecycleRegistryOwner;
import android.arch.lifecycle.ViewModelProviders;
import android.os.Bundle;
import android.support.annotation.CallSuper;
import android.support.annotation.Nullable;
import com.trello.rxlifecycle2.components.support.RxAppCompatActivity;


/**
 *
 * @author chenjinguang
 * @date 20.05.2017
 */
public abstract class BaseMVPActivity<V extends BaseMVPContract.View, P extends BaseMVPContract.Presenter<V>>
        extends RxAppCompatActivity implements BaseMVPContract.View, LifecycleRegistryOwner {

    private final LifecycleRegistry lifecycleRegistry = new LifecycleRegistry(this);
    protected P presenter;

    @SuppressWarnings("unchecked")
    @CallSuper
    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        BaseViewModel<V, P> viewModel = ViewModelProviders.of(this).get(BaseViewModel.class);
        boolean isPresenterCreated = false;
        if (viewModel.getPresenter() == null) {
            viewModel.setPresenter(initPresenter());
            isPresenterCreated = true;
        }
        presenter = viewModel.getPresenter();
        if(presenter != null){
            presenter.attachLifecycle(getLifecycle());
            presenter.attachView((V) this);
            if (!isPresenterCreated) {
                presenter.onPresenterCreated();
            }
        }
        setContentView(initLayoutId());
        initViewsAndEvents();
    }

    protected abstract int initLayoutId();

    protected abstract void initViewsAndEvents();

    @Override
    public LifecycleRegistry getLifecycle() {
        return lifecycleRegistry;
    }

    @CallSuper
    @Override
    protected void onDestroy() {
        super.onDestroy();
        if(presenter != null){
            presenter.detachLifecycle(getLifecycle());
            presenter.detachView();
        }
    }

    protected abstract P initPresenter();

}
